import router from '../../router'
import {RequestHandler} from 'express'
import 'reflect-metadata'

import {RequetMethod} from "./RequestMapping";
import {CommonUtil} from "../util/CommonUtil";


/**
 * 用于 Controller 类
 * @param root 路径
 * @constructor
 */
export function Controller(root?: string) {
    return function (target: new(...args: any[]) => any) {
        for (let key in target.prototype) {
            let path: string = Reflect.getMetadata('path', target.prototype, key)
            const method: RequetMethod = Reflect.getMetadata('method', target.prototype, key)
            const middleware: RequestHandler = Reflect.getMetadata('middleware', target.prototype, key)
            const handler = target.prototype[key]
            if (path && method) {

                path = CommonUtil.fullRequestPath(path)
                let fullpath = ''
                if (root) {
                    root = CommonUtil.fullRequestPath(root)
                    fullpath = root === '/' ? path : `${root}${path}`
                } else {
                    fullpath = path
                }

                if (middleware) {
                    // @ts-ignore
                    router[method](fullpath, middleware, handler)
                } else {
                    // @ts-ignore
                    router[method](fullpath, handler)
                }
            }
        }
    }
}
